package com.cennavi.minemapdemo.activity.mixlayer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.View;

import com.cennavi.minemapdemo.R;
import com.cennavi.minemapdemo.activity.BaseActivty;
import com.cennavi.minemapdemo.util.Config;
import com.cennavi.minemapdemo.util.DensityUtil;
import com.cennavi.minemapdemo.util.RandomUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.minedata.minemap.MinemapAccountManager;
import com.minedata.minemap.camera.CameraPosition;
import com.minedata.minemap.camera.CameraUpdateFactory;
import com.minedata.minemap.geometry.LatLng;
import com.minedata.minemap.map.MapView;
import com.minedata.minemap.map.MineMap;
import com.minedata.minemap.overlay.MarkerLayer;
import com.minedata.minemap.overlay.MarkerLayerOptions;
import com.minedata.minemap.overlay.OverlayFeature;
import com.minedata.minemap.overlay.Polygon;
import com.minedata.minemap.overlay.PolygonOptions;

import java.util.ArrayList;
import java.util.List;

/**
 * 覆盖物混合模式
 */
public class OverLayerMixedActivity extends BaseActivty {

    //地图视图
    private MapView mapView;
    //地图操作类
    private MineMap mineMap;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        MinemapAccountManager.getInstance(this, Config.MAP_TOK, Config.OFFLINE_TOK, Config.MAP_ID);
        setContentView(R.layout.activity_overlayer_mixed);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
        //初始化地图
        initMap();
    }
    public void zoomIn(View view){
        if (mineMap != null){
            mineMap.moveCamera(CameraUpdateFactory.zoomIn());
        }
    }

    public void zoomOut(View view){
        if (mineMap != null){
            mineMap.moveCamera(CameraUpdateFactory.zoomOut());
        }
    }

    private void initMap() {

        //mine map sdk 2.0.6之前生效
        // mapView.setStyleUrl(Config.mBaseUrl + Config.MAP_ID);
        mapView.setApiBaseUrl(Config.API_BASE_URL);
        mapView.setApiUrl(Config.API_URL);
        mapView.setSpriteImageUrl(Config.SPRITE_GLYPHS_URL);
        mapView.addMapRenderCallback(new MapView.OnMapReadyListener() {
            @Override
            public void onMapReady(MineMap oMineMap) {
                mineMap = oMineMap;
                mineMap.getUiSettings().setZoomControlsEnabled(false);
                mineMap.getUiSettings().setRotateGesturesEnabled(false);// 是否可以旋转地图
                mineMap.getUiSettings().setTiltGesturesEnabled(false);
                mineMap.setStyleUrl(Config.BASE_URL + Config.MAP_ID, new MineMap.OnStyleLoadedListener() {
                    @Override
                    public void onStyleLoaded(String s) {

                        //mine map sdk 2.0.6及之后版本这样使用
                        //layers 和 images 都在这里面加载
                        addImageToMap();
                    }
                });
                //设置指南针是否显示，默认是显示
                mineMap.getUiSettings().setCompassEnabled(true);
                mineMap.getUiSettings().setCompassGravity(Gravity.LEFT);
//                mineMap.getUiSettings().setCompassImage(getResources().getDrawable(R.mipmap.icon_compass));
                mineMap.getUiSettings().setCompassMargins(DensityUtil.dip2px(mContext, 11), DensityUtil.dip2px(mContext, 80),
                        0, 0);
                mineMap.setCameraPosition(
                        new CameraPosition.Builder().target(new LatLng(Config.mapCentrelat,Config.mapCentrelon)).zoom(14)
                                .tilt(0)//设定倾斜角度
                                .bearing(0) //摄像机指向的方向,从北部顺时针方向设置
                                .build());
                mineMap.setMaxZoomPreference(17);//设置最高展示级别，最高为17级别
                mineMap.setMinZoomPreference(3);//设置最低的展示级别


                mineMap.addOnMapClickListener(new MineMap.OnMapClickListener() {
                    @Override
                    public void onMapClick(@NonNull LatLng latLng) {
                        getMapEvent(latLng);

                    }
                });
            }

        });
    }
    //加载可能的图片资源
    private void addImageToMap() {


        icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher22);
        mineMap.addImage(R.mipmap.ic_launcher22+"", icon);

        icon1 = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.event_rtic_code1000_small);
        mineMap.addImage(R.mipmap.event_rtic_code1000_small+"", icon1);
    }
    private MarkerLayer markerLayer;// MarkerLayer
    private List<MarkerLayerOptions.MarkerItem> markerItemList;//marks
    private Bitmap icon = null , icon1 = null;


    private boolean getMapEvent(LatLng point) {
        boolean isHaveEvent = false;
        //捕捉事件
        PointF screenLoc = mineMap.getProjection().toScreenLocation(point);
        float offsize = 20f;
        RectF box = new RectF(screenLoc.x - offsize, screenLoc.y + offsize, screenLoc.x + offsize, screenLoc.y - offsize);
        List<OverlayFeature> featuresEvent = this.mineMap.queryRenderedFeatures(box, "markerLayer");

        if (featuresEvent.size() > 0) {
            //点击其中一个事件
            for (int i = 0; i < featuresEvent.size(); i++) {
                try {
                    String evendesc = featuresEvent.get(i).toJson();
                    snackbar(this.mapView, evendesc);

                    isHaveEvent = true;
                    break;
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }

        return isHaveEvent;
    }


    private List<Polygon> polygons;

    /**************面*************/
    public void addPolygon(View view) {
        LatLng[] lines = new LatLng[]{RandomUtil.randomLatLon(), RandomUtil.randomLatLon(), RandomUtil.randomLatLon()};
        Polygon polygon = mineMap.addPolygon(new PolygonOptions()
                .add(lines)
                .fillColor(RandomUtil.randomColor())
                .alpha(0.5f)
                .strokeColor(RandomUtil.randomColor()));
        if (polygons == null) {
            polygons = new ArrayList<>();
        }
        polygons.add(polygon);
    }

    public void removePolygon(View view) {
        if (polygons != null && polygons.size() > 0)
            for (Polygon polygon : polygons) {
                mineMap.removePolygon(polygon);
            }
        polygons.clear();
//            mineMap.clear();
    }

    public void movePolygon(View view) {
        if (polygons != null && polygons.size() > 0)
            for (Polygon polygon : polygons) {
                List<LatLng> lines = new ArrayList<>();
                lines.add(RandomUtil.randomLatLon());
                lines.add(RandomUtil.randomLatLon());
                lines.add(RandomUtil.randomLatLon());
                polygon.setPoints(lines);
            }

    }


    //加点
    public void addmarklayer(View view) {
        if (markerItemList == null) {
            markerItemList = new ArrayList<>();
        }
        //绘制marklayer
        if (icon == null) {
            icon = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher22);
        }
        LatLng latLng = RandomUtil.randomLatLon();

        MarkerLayerOptions.MarkerItem markerItem = new MarkerLayerOptions.MarkerItem().icon(R.mipmap.ic_launcher22+"").position(latLng);
        markerItem.markerInfo(marklayerfeatureProperties(System.currentTimeMillis() + "", 3 + ""));
        updataMarks(markerItem);
    }

    public void onMove(View view) {
        for (MarkerLayerOptions.MarkerItem markerItem : markerItemList) {
            markerItem.position(new LatLng((markerItem.getPosition().getLatitude() - 0.001), markerItem.getPosition().getLongitude()));
        }

        if (markerLayer != null || markerLayer.isLayerExist()) {
            markerLayer.update();
        }
    }

    public void onGone(View view) {
        if (markerLayer != null || markerLayer.isLayerExist()) {
            markerLayer.setVisible(MarkerLayerOptions.NONE);
        }
    }

    public void onVisible(View view) {
        if (markerLayer != null || markerLayer.isLayerExist()) {
            markerLayer.setVisible(MarkerLayerOptions.VISIBLE);
        }
    }

    public void checkIcon(View view) {

        for (MarkerLayerOptions.MarkerItem markerItem : markerItemList) {
            //id一定要跟之前不一样 要不更换不成功
            markerItem.icon(R.mipmap.event_rtic_code1000_small+"");
        }

        if (markerLayer != null || markerLayer.isLayerExist()) {
            markerLayer.update();
        }
    }

    //刷新层
    private void updataMarks(MarkerLayerOptions.MarkerItem markerItem) {
        if (markerLayer == null || !markerLayer.isLayerExist()) {
            MarkerLayerOptions options = new MarkerLayerOptions("markerLayer");
            options.add(markerItem);
            options.iconAnchor(MarkerLayerOptions.ANCHOR_CENTER);//基准点
//                    .iconAllowOverlap(false)
//                    .iconIgnorePlacement(false)//图标碰撞
//                    .textAllowOverlap(false)
//                    .textIgnorePlacement(false)//文字碰撞

            options.iconPitchAlignment(MarkerLayerOptions.PITCH_ALIGNMENT_MAP);//平的还是随着地图阳角而变化
            markerLayer = mineMap.addLayer(options);
            markerItemList.add(markerItem);
        } else {
            if (markerLayer.isLayerExist()) {
                markerLayer.add(markerItem);
                markerLayer.update();
                markerItemList.add(markerItem);
            }
        }
    }

    private JsonObject marklayerfeatureProperties(String eventId, String type) {
        JsonObject object = new JsonObject();
        object.add("mId", new JsonPrimitive(eventId));
        object.add("type", new JsonPrimitive(type));
        return object;
    }

    //生命周期
    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null)
            mapView.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mapView != null)
            mapView.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null)
            mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //2.0.6及之后版本 需要将加入地图的图片资源进行清理
        if (mineMap != null)
            mineMap.removeImagesAll();


        if (mapView != null)
            mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (mapView != null){
            mapView.onLowMemory();
        }
    }

}
